﻿/*
 * Autore: Artur Tolstenco
 */

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using RecipesManager.Data;
using RecipesManager.MainControls.IngredientSubControls;
using RecipesManager.RecipesImporter;

namespace RecipesManager.MainControls.RecipeSubControls
{
    /// <summary>
	/// Interaction logic for ImportPreview.xaml
    /// </summary>
    public partial class ImportPreview
    {
        ImportedRecipe _currentRecipe;
	    List<string> ingred;
	    List<MeasureUnit> units;

		public ImportPreview()
        {
           InitializeComponent();

		   ingred=new List<string>();
		   foreach (var ingredient in Manager.Ingredients)
			   ingred.Add(ingredient.Name.ToLower());

			units=new List<MeasureUnit>();
			foreach (var measure in Manager.Measures)
			{
				units.Add(new MeasureUnit(measure.Name, measure.ShortName.ToLower()));	
			}

            bt_chiudi.IsCancel = true;
        }

		public ImportedRecipe CurrentRecipe
        {
            get { return _currentRecipe; }
            set
            {
                if (value == null)
                    return;

                _currentRecipe = value;
                tb_title.Text = Application.Current.FindResource("ImportPreviewTitleTooltip") + _currentRecipe.Name;
				tb_warning.Text = Application.Current.FindResource("ImportPreviewWarningTooltip") + "";
				tb_warning2.Text = Application.Current.FindResource("ImportPreviewWarning2Tooltip") + "";

                WriteOriginalRecipe();
            }
        }

        void WriteOriginalRecipe()
        {
            if (_currentRecipe == null)
                return;

            var str = "";

            str += "Nome ricetta: " + _currentRecipe.Name + Environment.NewLine;
            str += "Originale preso da: " + _currentRecipe.OriginalSource + Environment.NewLine;
            str += "Tempo di esecuzione: " + (_currentRecipe.PreparationHours>=0 ? _currentRecipe.PreparationHours.ToString(CultureInfo.InvariantCulture) : "??") + " ore e " +
                   (_currentRecipe.PreparationMinutes>=0 ? _currentRecipe.PreparationMinutes.ToString(CultureInfo.InvariantCulture) : "??") + " minuti" + Environment.NewLine;
            if (_currentRecipe.Servings!=-10000) str += "Numero porzioni: " + _currentRecipe.Servings + Environment.NewLine;
			else str += "Numero porzioni: " + Environment.NewLine;
            str += "Famiglia unità di misura: " + _currentRecipe.MeasuringUnit +
                   Environment.NewLine;

            str += Environment.NewLine;
            str += "Lista ingredienti:" + Environment.NewLine;

	        foreach (var i in _currentRecipe.Ingredients)
	        {
		        if (!ingred.Contains(i.Name.ToLower())) str += "*";
		        str += "Nome ingrediente: " + i.Name + "; Note: " + i.Note + "; Quantità: " + i.getQuantityNumber();
		        if (units.Contains(new MeasureUnit(i.getQuantityMeasure().ToLower()))) str+=" " +i.getQuantityMeasure();
				else str += " **" + i.getQuantityMeasure();       
				str += ";" + Environment.NewLine;
	        }


	        str += Environment.NewLine;
            str += "Lista passi:" + Environment.NewLine;

            foreach (var s in _currentRecipe.Steps)
            {
                if (s.Contains("<sub>")) str += " - " + s.Replace("<sub>","") + " [CONTIENE UNA SOTTORICETTA];";
				else str += " - " + s + ";";
                
                str += Environment.NewLine;
            }

			str += Environment.NewLine;
			str += "Lista prove:" + Environment.NewLine;

			foreach (var t in _currentRecipe.Trials) {
				str += " - " + t + ";";
				str += Environment.NewLine;
			}

            tb_description.Text = str;

        }

        private void Bt_Chiudi_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

		private void Bt_Ok_Click(object sender, RoutedEventArgs e)
		{
			bool ok = true;
			foreach (var i in _currentRecipe.Ingredients)
			{
				if (!ingred.Contains(i.Name.ToLower()) && ok) {
					var addIngr = new IngredientAddWindow();
					addIngr.SetIngredientName(i.Name);
					var res = addIngr.ShowDialog();
					if (res == false)
					{
						ok = false;
						MessageBox.Show("Per importare la ricetta, vanno creati tutti gli ingredienti mancanti.", "Avviso",
									MessageBoxButton.OK,
									MessageBoxImage.Error);
						ingred = new List<string>();
						foreach (var ingredient in Manager.Ingredients)
							ingred.Add(ingredient.Name.ToLower());
					}
				}
			}
			if (ok)
			{
				ImportRecipeIntoDB();
				Close();
			}
			
		}
		
		void ImportRecipeIntoDB() {
			try {
				var recipe = Manager.Recipes.Add(_currentRecipe.Name,
												_currentRecipe.OriginalSource,
												GetMeasureFamilyType(
													_currentRecipe.MeasuringUnit),
												_currentRecipe.PreparationHours as int?,
												_currentRecipe.PreparationMinutes as int?,
												_currentRecipe.Servings as int?);

				foreach (var i in _currentRecipe.Ingredients)
				{
					recipe.Ingredients.Add(i.Name, getLongMeasure(i.getQuantityMeasure()), i.getQuantityNumber(), i.Note);
				}

				foreach (var s in _currentRecipe.Steps)
				{
					if (s.Contains("<sub>")) recipe.Steps.AddGeneric(s.Replace("<sub>", "") + " [MODIFICARE IN SOTTORICETTA]");
					else recipe.Steps.AddGeneric(s);
				}

				foreach (var t in _currentRecipe.Trials)
					recipe.Trials.Add(t);


			} catch (Exception e) {
				MessageBox.Show(e.Message, (string)Application.Current.FindResource("notification_dialog_type"),
									MessageBoxButton.OK,
									MessageBoxImage.Error);
			}
		}

		static MeasureFamily GetMeasureFamilyType(string s) {
			if (s == null)
				return MeasureFamily.None;

			if (s.ToLower().Equals(Properties.Resources.MetricMeasureFamily.ToLower()))
				return MeasureFamily.Metric;
			return s.ToLower().Equals(Properties.Resources.UKMeasureFamily.ToLower()) ? MeasureFamily.UK : MeasureFamily.USA;
		}

	    string getLongMeasure(string sh)
	    {
		    foreach (var m in units)
			    {
				    if (m.Equals(new MeasureUnit(sh))) return m.longName;
			    }
		    return "Grammi"; //Valore di default in caso l'unità di misura non venga trovata
	    }
		
    }

	class MeasureUnit
	{
		public string longName;
		public string shortName;
    

		public MeasureUnit()
		{
		}

		public MeasureUnit(string l, string s )
		{
			longName = l;
			shortName = s;
		}

		public MeasureUnit(string s) {
			shortName = s;
		}

		public override bool Equals (object obj)
		{

			if (obj == null || GetType() != obj.GetType()) 
			{
				return false;
			}
			var mUnit = (MeasureUnit) obj;
        
			// TODO: write your implementation of Equals() here
			return Equals(shortName,  mUnit.shortName);
		}
    
		// override object.GetHashCode
		public override int GetHashCode()
		{
			// TODO: write your implementation of GetHashCode() here
			return shortName.GetHashCode();
		}

	}
}
